package cn.xxstudy.blog.service

import cn.xxstudy.blog.dao.TagsRepository
import cn.xxstudy.blog.entity.Tags
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional


/**
 * 作者：wuxinxi on 2020/11/25
 * 包名：cn.xxstudy.blog.service
 * TODO:标签表实现
 */
@Service
class TagsService : ITagsService {
    @Autowired
    private lateinit var tagsRepository: TagsRepository

    override fun createTags(tags: Tags): Tags? = tagsRepository.save(tags)

    override fun getTagsById(id: Long): Tags? = tagsRepository.getOne(id)

    override fun getTagsByName(tagName: String): Tags? = tagsRepository.findTagsByTagName(tagName)

    override fun listTags(pageable: Pageable): Page<Tags> = tagsRepository.findAll(pageable)

    override fun listTags(): List<Tags>? = tagsRepository.findAll()

    override fun listTags(ids: String): List<Tags> {
        val longIds = ids.split(",").map { it.toLong() }
        return tagsRepository.findAllById(longIds)
    }

    override fun listTagsTop(size: Int): List<Tags> {
       val sort=Sort.by(Sort.Direction.DESC,"blogs.size")
        val pageable=PageRequest.of(0,size,sort)
        return tagsRepository.findTop(pageable)
    }

    @Transactional
    override fun deleteById(id: Long): Boolean {
        return try {
            tagsRepository.deleteById(id)
            true
        } catch (e: Exception) {
            false
        }
    }

    @Transactional
    override fun deleteByName(tagName: String): Boolean = tagsRepository.deleteTagsByTagName(tagName) > 0

    @Transactional
    override fun updateByName(tagName: String, sourceTags: Tags): Boolean {
        val tags = getTagsByName(tagName) ?: false
        BeanUtils.copyProperties(sourceTags, tags)
        return try {
            tagsRepository.save(tags as Tags)
            true
        } catch (e: Exception) {
            false
        }
    }

}